package com.jx.smartbot.controller;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
//import java.util.ArrayList;
import java.util.Base64;
//import java.util.List;
//import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
//import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.gocom.imoss.common.Exception.AuthorizedException;
//import com.gocom.imoss.common.Exception.ForbiddenException;
//import com.gocom.imoss.common.Exception.NotFoundException;
import com.jx.smartbot.VO.callback.GroupData;
//import com.jx.smartbot.VO.callback.GroupPlussDetails;
import com.jx.smartbot.VO.callback.GroupTemplate;
import com.jx.smartbot.VO.callback.GroupUserCheckData;
import com.jx.smartbot.VO.callback.GroupUsers;
import com.jx.smartbot.VO.callback.GroupplusData;
import com.jx.smartbot.VO.callback.Tool;
import com.jx.smartbot.VO.callback.UserData;
import com.jx.smartbot.VO.gocome.TokenData;
import com.jx.smartbot.service.IRedisService;
import com.jx.smartbot.service.SystemSuperApp;
import com.jx.smartbot.util.JacksonUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/wps")
@Api(value = "GoComCallBackService",description="客户端调用wp时提供的服务")
public class GoComCallBackService extends BaseController {
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(GoComCallBackService.class);
	@Autowired
	SystemSuperApp systemSuperApp;
	@Resource(name="wpServiceUrl")
	String wpServiceUrl;
	@Autowired
	RestTemplate restTemplate;
   @Autowired
	IRedisService redisService;
/*private void isAuthory(String wptoken){
		if(wptoken.startsWith("wp_")){
			wptoken=wptoken.substring(3);
		}
		if(!redisService.exists(wptoken)){
			throw new AuthorizedException();
		}
	}*/
	
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "token2user", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "将wp_token转为userid和device", notes = "")  
	public TokenData tlist(
			@RequestParam(value="wptoken",  required=true) String wptoken,
			HttpServletRequest request) {
		//this.isAuthory(wptoken);
		if(wptoken.startsWith("wp_")){
			wptoken=wptoken.substring(3);
		}
		String userid=redisService.hGet(wptoken,"userid");
		String device=redisService.hGet(wptoken,"device");
		return new TokenData(userid,device);
	}
	
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "alltools", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "工具列表", notes = "取得工具列表")  
	public Tool alltools(
			//UserData userData,
			@RequestParam(value="wptoken",  required=true) String wptoken,
			@RequestParam(value="pgIndex", defaultValue="0") int pgIndex,
			@RequestParam(value="pgCount", defaultValue="6") String pgCount,
			@RequestParam(value="data", defaultValue="") String data,
			HttpServletRequest request) throws UnsupportedEncodingException{
		UserData userData=null;
	//	this.isAuthory(wptoken);
		//pgIndex--;
		if(!data.equals("")){
			data=URLDecoder.decode(data,"utf-8");
			data=data.replaceAll("%2b", "+");
			data=data.replaceAll(" ", "+");
			byte[]  b=Base64.getDecoder().decode(data);
			String value=new String(b,"utf-8");
			userData=JacksonUtil.readValue(value, UserData.class);
		}
		//GET /imoss/api/imoss/groupsTools
		String urlString=wpServiceUrl + "/imoss/api/imoss/tools?pgCount="+pgCount;
		urlString+="&pgIndex="+pgIndex;
		urlString+="&status=1";
		URI uri = URI.create(urlString);   
		String jsonStr=restTemplate.getForObject(uri,String.class);
		//jsonStr=jsonStr.replace("%token%", wptoken);
		Tool tools=JacksonUtil.readValue(jsonStr, Tool.class);
		TokenData t= tlist(wptoken,request);
		 String device=t.getDevice();
		for(Tool.Elements te:tools.getElements()){
			String address=te.getPcAddress().replace("%token%", wptoken);
			if(!device.equals("pc")){
				address=te.getMobileAddress().replace("%token%", wptoken);
			}
			if(userData!=null){
				String dtype=userData.getType();
				String dto=userData.getTo();
				if(dtype!=null &&dtype.equals("grp")){
					if(dto!=null && !dto.equals("")){
						address=address.replace("%groupid%", dto);
					}
				}
			}
			address=address.replace("%groupid%", "");
			//logger.info(address);
			te.setAddress(address);
			te.setUserData(userData);
			te.setAppId(null);
			te.setAppKey(null);
			//te.setAssistantName(null);
			te.setMobileAddress(null);
			te.setPcAddress(null);
			te.setNativeAddress(null);
			te.setManagerAddress(null);
			te.setLightAppId(null);
			te.setSuperAppId(null);
			te.setFirstToolClassName(null);
			te.setSecondToolClassName(null);
		}
		return tools;
	}

	@CrossOrigin(origins = "*")
	@RequestMapping(value = "groupplus", method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "群增强", notes = "")  
	public void groupplus(
			@RequestParam(value="wptoken",  required=true) String wptoken,
			@RequestBody  GroupplusData Datajson,
			HttpServletRequest request){
		//this.isAuthory(wptoken);
		String urlString=wpServiceUrl + "/imoss/api/imoss/group";
		//String st=JacksonUtil.toJSon(Datajson);
		//logger.info(JacksonUtil.toJSon(Datajson));
		restTemplate.postForObject(urlString,Datajson,String.class);
		///logger.debug(ss);
		
	}
	
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "groupplus/id", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "群增强ID", notes = "从交换传回的群ID")  
	public GroupData groupplus_id(
			@RequestParam(value="wptoken",  required=true) String wptoken,
			@RequestParam(value="data", defaultValue="") String data,
			HttpServletRequest request) throws UnsupportedEncodingException{
		//this.isAuthory(wptoken);
		if(data.equals("")){
			return null;
		}
		data=URLDecoder.decode(data,"utf-8");
		data=data.replaceAll("%2b", "+");
		data=data.replaceAll(" ", "+");
		byte[]  b=Base64.getDecoder().decode(data.trim());
		//byte[]  b=Base64.getUrlDecoder().decode(data.trim());
		String value=new String(b,"utf-8");
		GroupData groupData=JacksonUtil.readValue(value, GroupData.class);
		return groupData;
	}
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "wpgrouptemplate", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "群模板列表", notes = "获取群模板服务对象列表")  
	public GroupTemplate wpgrouptemplate(
			@RequestParam(value="wptoken",  required=true) String wptoken,
			HttpServletRequest request){
		//this.isAuthory(wptoken);
		String urlString=wpServiceUrl + "/imoss/api/imoss/groupTemplates";
		URI uri = URI.create(urlString);   
		GroupTemplate temple=restTemplate.getForObject(uri,GroupTemplate.class);
		return temple;
	}
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "takeusers", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "域用户列表", notes = "根据查询条件获取用户服务对象列表")  
	public GroupUsers takeusers(
			@RequestParam(value="wptoken",  required=true) String wptoken,
			@RequestParam(value = "domain", defaultValue = "",required=false)String domain,
			@RequestParam(value="maindeptid", defaultValue="",required=false) String maindeptid,
			HttpServletRequest request){
		//this.isAuthory(wptoken);
		String urlString=wpServiceUrl + "/imoss/api/imoss/users?domain="+domain;
		urlString=urlString+"&maindeptid="+maindeptid;
		URI uri = URI.create(urlString);   
		GroupUsers users=restTemplate.getForObject(uri,GroupUsers.class);
		return users;
	}
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "usercheck", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "查询用户", notes = "根据查询条件获取用户")  
	public GroupUserCheckData userCheck(
			@RequestParam(value="wptoken",  required=true) String wptoken,
			@RequestParam(value = "groupid", defaultValue = "")String groupid,
			@RequestParam(value="userId", defaultValue="") String userId,
			HttpServletRequest request){
		//this.isAuthory(wptoken);
		String urlString=wpServiceUrl + "/imoss/api/imoss/ppGroupUsers?ppGuid="+groupid;
		urlString=urlString+"&userId="+userId;
		URI uri = URI.create(urlString);   
		GroupUserCheckData users=restTemplate.getForObject(uri,GroupUserCheckData.class);
		return users;
	}
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "groupiddetails", method = RequestMethod.GET,produces="application/json")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "获取增强群详情(GroupID)", notes = "")  
	public String groupPlusDetails4Id(
			@RequestParam(value="wptoken",  required=true) String wptoken,
			@RequestParam(value = "ppGuid", defaultValue = "")String ppGuid,
			HttpServletRequest request,HttpServletResponse response){
		//this.isAuthory(wptoken);
		String urlString=wpServiceUrl + "/imoss/api/imoss/groups/"+ppGuid;
		//urlString=urlString+"&userId="+userId;
		URI uri = URI.create(urlString);   
		String rt=restTemplate.getForObject(uri,String.class);
		response.setContentType("application/json");
		return rt;
	}
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "groupdetails", method = RequestMethod.GET,produces="application/json")
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "获取增强群详情(data)", notes = "")  
	public String groupPlusDetails(
			@RequestParam(value="wptoken",  required=true) String wptoken,
			@RequestParam(value="data",  required=true) String data,
			HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		GroupData groupData=groupplus_id(wptoken,data,request);
		if( groupData==null){
			return null;
		}
		response.setContentType("application/json");
		return groupPlusDetails4Id(wptoken,groupData.getGroupid(),request,response);
	}
	/*@CrossOrigin(origins = "*")
	@RequestMapping(value = "t2t", method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.OK)
	@ApiOperation(value = "tttttttttttt", notes = "")  
	public GoComMessage4TextTT t2t(
			@RequestBody  GoComMessage4TextTT Datajson,
			HttpServletRequest request){
		return Datajson;
	}*/
}
